<?php
/**
 * Yjnic_Sae_Cache sae缓存
 *
 * @package     Yjnic\Sae
 * @author      prettyyjnic <prettyyjnic@qq.com> 2015-11-22
 */

class Yjnic_Sae_Cache implements PhalApi_Cache {

    protected $_ins;
    protected $_configs;

    public function __construct($configs=array()) {
        $this->_ins = new Memcache;
        if (!$this->_ins->connect()) {
            throw new Yjnic_Sae_Exception("Can not connect to memcache", 503);   
        }        
        $this->_configs = $configs;
    }

    /**
     * 设置缓存
     * 
     * @param string $key 缓存key
     * @param mixed $value 缓存的内容
     * @param int $expire 缓存有效时间，单位秒，非时间戳
     */
    public function set($key, $value, $expire = 600){
        return $this->_ins->set( $this->_formatKey($key), serialize($value), false, $expire);
    }

    /**
     * 读取缓存
     * 
     * @param string $key 缓存key
     * @return mixed 失败情况下返回NULL
     */
    public function get($key){
        $value = $this->_ins->get( $this->_formatKey($key) );
        return $value !== FALSE ? @unserialize($value) : NULL;
    }

    /**
     * 删除缓存
     * 
     * @param string $key
     */
    public function delete($key){
        return $this->_ins->delete($this->_formatKey($key));
    }

    protected function _formatKey($key) {
        return $this->_configs['prefix'] . $key;
    }
}

